/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-08 15:07:43
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.api.dataaccess.DataAccessService;
import com.joysuch.wwyt.api.dataaccess.OrientationDataSyncService;
import com.joysuch.wwyt.bp.bean.contractor.BpCertExpireRemindBean;
import com.joysuch.wwyt.bp.bean.contractor.BpContractorBean;
import com.joysuch.wwyt.bp.bean.contractor.BpContractorCertBean;
import com.joysuch.wwyt.bp.bean.contractor.BpContractorNameDto;
import com.joysuch.wwyt.bp.entity.BpEnterpriseInfo;
import com.joysuch.wwyt.bp.entity.contractor.BpContractor;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorCert;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorCertRemind;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.enums.ContractorTypeEnum;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.bp.repository.BpContractorCertDao;
import com.joysuch.wwyt.bp.repository.BpContractorCertRemindDao;
import com.joysuch.wwyt.bp.repository.BpContractorDao;
import com.joysuch.wwyt.bp.repository.BpContractorStaffDao;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpEnterpriseInfoDao;
import com.joysuch.wwyt.bp.service.BpContractorService;
import com.joysuch.wwyt.bp.service.BpContractorStaffService;
import com.joysuch.wwyt.common.entity.CommonIndexNotify;
import com.joysuch.wwyt.common.enums.CommonIndexNotifyTypes;
import com.joysuch.wwyt.common.repository.CommonIndexNotifyDao;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.bean.SimpleInfoBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.edu.bean.EduCertEditUserNameBean;
import com.joysuch.wwyt.edu.enums.CertificateRemindTypes;
import com.joysuch.wwyt.util.SnowFlakeUtil;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class BpContractorServiceImpl implements BpContractorService {

    @Autowired
    private BpContractorDao dao;
    @Autowired
    private BpContractorCertDao bpContractorCertDao;
    @Autowired
    private BpContractorCertRemindDao bpContractorCertRemindDao;
    @Autowired
    private BpContractorStaffDao bpContractorStaffDao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private CommonIndexNotifyDao notifyDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BpEnterpriseInfoDao bpEnterpriseInfoDao;
    @Autowired
    private DataAccessService dataAccessService;
    @Autowired
    private OrientationDataSyncService orientationDataSyncService;
    @Autowired
    private BpContractorStaffService bpContractorStaffService;
    @Autowired
    private BaseConfigService baseConfigService;


    @Override
    public ResultBean save(BpContractorBean bean) {
        Long id = bean.getId();
        String companyName = bean.getCompanyName();
        BpContractor bpContractor;
        if (id == null) {
            int count = dao.countByName(companyName);
            if (count > 0) {
                return ResultBean.fail(101, "此承包商单位名称已存在");
            }
            bpContractor = new BpContractor();
            bpContractor.setCode(bizCodeGeneratorFacade.chengbaoshang());
            bpContractor.setState(DataStateTypes.EFFECTIVE.getState());
            bpContractor.setUniqueId(SnowFlakeUtil.getContractorId());
        } else {
            bpContractor = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("系统繁忙"));
            if (DataStateTypes.UN_EFFECTIVE.getState().equals(bpContractor.getState())) {
                return ResultBean.fail(101, "此数据已作废");
            }
            int integer = dao.countByNameAndIdNotEq(companyName, id);
            if (integer > 0) {
                return ResultBean.fail(101, "此承包商单位名称已存在");
            }
        }
        BeanUtils.copyProperties(bean, bpContractor, "code", "state", "dutyScriptRemindOrNot");
        bpContractor.setBusinessType(getListJson(bean.getBusinessTypeList()));
        BaseAttachmentBean dutyScriptAttachment = bean.getDutyScriptAttachment();
        bpContractor.setDutyScriptAttachment(dutyScriptAttachment == null ? null : JSON.toJSONString(dutyScriptAttachment));
        BpContractor save = dao.save(bpContractor);
        Long certId = save.getId();
        List<Long> contractorCertIdList = bean.getContractorCertIdList();
        //数据设置主表id
        if (!CollectionUtils.isEmpty(contractorCertIdList)) {
            List<BpContractorCert> contractorCertList = bpContractorCertDao.findAllById(contractorCertIdList);
            if (!CollectionUtils.isEmpty(contractorCertList)) {
                for (BpContractorCert bpContractorCert : contractorCertList) {
                    bpContractorCert.setContractorId(certId);
                }
                bpContractorCertDao.saveAll(contractorCertList);
            }
        }
        //添加通知
        int flag = 0;
        LocalDate dutyScriptExpireDate = bean.getDutyScriptExpireDate();
        flag = notifyByCurData(id, save.getDutyScriptRemindOrNot(), flag, dutyScriptExpireDate);
        //判断有没有提醒配置
        Pair<Boolean, BpContractorCertRemind> pair = remindOrNot();
        if (pair.getKey()) {
            List<CommonIndexNotify> notifyList = Lists.newArrayList();
            //需要通知的人员ids
            BpContractorCertRemind remind = pair.getValue();
            List<Long> remindUserIdList = getRemindUserIdList(remind);
            Integer hours = CertificateRemindTypes.getHours(remind.getRemindType());
            if (flag == 1) {
                //承包商责任书
                getContractorDutyNotifyList(hours, remindUserIdList, notifyList, save);
                save.setDutyScriptRemindOrNot(1);
                dao.save(save);
            }
            //承包商资质证书
            List<BpContractorCert> certList = bpContractorCertDao.findRemindTaskAndContractorId(certId);
            if (!CollectionUtils.isEmpty(certList)) {
                for (BpContractorCert cert : certList) {
                    getContractorQualityCert(hours, remindUserIdList, notifyList, cert);
                    cert.setDutyScriptRemindOrNot(1);
                }
                bpContractorCertDao.saveAll(certList);
            }
            notifyDao.saveAll(notifyList);
        }
        //调数据接入接口
        dataAccessService.contractor(save);
        batchSyncData(Lists.newArrayList(save));
        return ResultBean.defaultSuccessResult();
    }

    private int notifyByCurData(Long id, Integer dutyScriptRemindOrNot, int flag, LocalDate dutyScriptExpireDate) {
        if (dutyScriptExpireDate != null) {
            if (id == null) {
                //新增
                flag = 1;
            } else {
                if (dutyScriptRemindOrNot == 0) {
                    //新增
                    flag = 1;
                }
            }
        }
        return flag;
    }

    @Override
    public ResultBean page(Pageable pageable, String contractorType,Boolean locateSync, String companyName) {
        pageable = PageDataUtils.addOrderByDesc(pageable, "id");
        Specification<BpContractor> specification = (Root<BpContractor> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) -> {
            List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("state"), DataStateTypes.EFFECTIVE.getState()));
            if (contractorType != null) {
                predicates.add(cb.equal(root.get("contractorType"), contractorType));
            }
            if (null != locateSync){
                predicates.add(cb.equal(root.get("locateSync"),locateSync));
            }
            if ( StringUtils.isNotEmpty(companyName)){
                predicates.add(cb.like(root.get("companyName"), "%" + companyName + "%" ) );
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<BpContractor> page = dao.findAll(specification, pageable);
        for (BpContractor bpContractor : page) {
            LocalDate expireDate = bpContractor.getDutyScriptExpireDate();
            //责任书是否有效
            if (expireDate == null || LocalDate.now().isAfter(expireDate)) {
                bpContractor.setDutyScriptEffectiveOrNot("否");
            }
            //证书是否有效  判断资质证书,没有证书: 否; 只要有一个证书过期: 否
            List<BpContractorCert> certList = bpContractorCertDao.findByContractorIdAndState(bpContractor.getId(),
                    DataStateTypes.EFFECTIVE.getState());
            if (CollectionUtils.isEmpty(certList)) {
                bpContractor.setCertEffectiveOrNot("否");
            } else {
                int count = 0;
                for (BpContractorCert cert : certList) {
                    LocalDate certExpireDate = cert.getCertExpireDate();
                    if (certExpireDate != null && LocalDate.now().isAfter(certExpireDate)) {
                        bpContractor.setCertEffectiveOrNot("否");
                        break;
                    } else if (certExpireDate == null) {
                        count++;
                    }
                }
                if (count == certList.size()) {
                    bpContractor.setCertEffectiveOrNot("否");
                }
            }
        }
        return ResultBean.pageData(page.getContent(), page.getTotalElements());
    }

    @Override
    public ResultBean allContractor() {
        List<BpContractor> contractorList = dao.findAllContractor();
        if (CollectionUtils.isEmpty(contractorList)) {
            return ResultBean.success(null);
        }
        List<BpContractorNameDto> collect = contractorList.stream().map(r ->
                new BpContractorNameDto(r.getId(), r.getCompanyName(), 1)).collect(Collectors.toList());
        return ResultBean.success(collect);
    }

    @Override
    public ResultBean nullify(Long id) {
        Assert.notNull(id, "id cannot be null");
        BpContractor contractor = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("承包商不存在"));
        List<BpContractor> list = new ArrayList<>();
        list.add(contractor);
        List<BpContractorStaff> staffs = bpContractorStaffDao.findByContractorId(id);
        if (!CollectionUtils.isEmpty(staffs)) {
            throw new IllegalArgumentException("该承包商单位(" + contractor.getCompanyName() + ")存在人员，请先移除人员后再删除承包商单位");
        }
        dao.nullify(id);
        //人员定位同步数据
        orientationDataSyncService.contractor(list, "deleteContractor");
        //承包商作废，对应的承包商人员一并作废
//        List<BpContractorStaff> staffs = bpContractorStaffDao.findByContractorId(id);
//        for (BpContractorStaff staff : staffs) {
//            bpContractorStaffService.nullify(staff.getId());
//        }
//        bpContractorStaffDao.nullify(id);

        return ResultBean.defaultSuccessResult();
    }

    @Override
    public ResultBean batchNullify(List<Long> ids) {
        List<String> message = new ArrayList<>();
        if (org.springframework.util.CollectionUtils.isEmpty(ids)) {
            throw new IllegalArgumentException("请选择要删除的承包商单位");
        }
        for (Long id : ids) {
            try {
                nullify(id);
            } catch (IllegalArgumentException e) {
                message.add(e.getMessage());
                log.error(e.getMessage(), e);
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
        return ResultBean.success(message);
    }

    @Override
    public ResultBean getById(Long id) {
        Assert.notNull(id, "id cannot be null");
        BpContractor bpContractor = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("此数据不存在"));
        BpContractorBean bpContractorBean = new BpContractorBean();
        BeanUtils.copyProperties(bpContractor, bpContractorBean);
        bpContractorBean.setBusinessTypeList(convertJsonToList(bpContractor.getBusinessType(), Integer.class));
        String attachment = bpContractor.getDutyScriptAttachment();
        bpContractorBean.setDutyScriptAttachment(attachment == null ? null : JSONObject.parseObject(attachment, BaseAttachmentBean.class));
        //承包商资质证书详情
        List<BpContractorCert> certList = bpContractorCertDao.findByContractorIdAndState(id, DataStateTypes.EFFECTIVE.getState());
        if (!CollectionUtils.isEmpty(certList)) {
            List<BpContractorCertBean> contractorCertList = Lists.newArrayList();
            for (BpContractorCert contractorCert : certList) {
                BpContractorCertBean bpContractorCertBean = new BpContractorCertBean();
                BeanUtils.copyProperties(contractorCert, bpContractorCertBean);
                String json = contractorCert.getAttachmentJson();
                bpContractorCertBean.setAttachment(json == null ? null : JSONObject.parseObject(json, BaseAttachmentBean.class));
                //过期判断
                LocalDate certExpireDate = contractorCert.getCertExpireDate();
                if (certExpireDate == null || !LocalDate.now().isAfter(certExpireDate)) {
                    bpContractorCertBean.setExpireFlag(null);
                }
                contractorCertList.add(bpContractorCertBean);
            }
            bpContractorBean.setContractorCertList(contractorCertList);
        }
        //查询该承包商管理部门的名称
        String responsibleDeptName = dao.selectResponsibleDeptName(bpContractor.getResponsibleDept());
        bpContractorBean.setResponsibleDeptName(responsibleDeptName);
        return ResultBean.success(bpContractorBean);
    }

    @Override
    public BpContractor get(Long id) {
        return dao.findById(id).orElse(null);
    }

    @Override
    public ResultBean contractorCertSave(BpContractorCertBean bean) {
        Long id = bean.getId();
        BpContractorCert bpContractorCert;
        if (id == null) {
            bpContractorCert = new BpContractorCert();
            bpContractorCert.setState(DataStateTypes.EFFECTIVE.getState());
        } else {
            bpContractorCert = bpContractorCertDao.findById(id).orElseThrow(() -> new IllegalArgumentException("数据不存在"));
            if (DataStateTypes.UN_EFFECTIVE.getState().equals(bpContractorCert.getState())) {
                return ResultBean.fail(101, "此数据已作废");
            }
        }
        BeanUtils.copyProperties(bean, bpContractorCert, "state", "dutyScriptRemindOrNot");
        BaseAttachmentBean attachment = bean.getAttachment();
        bpContractorCert.setAttachmentJson(attachment == null ? null : JSON.toJSONString(attachment));
        BpContractorCert save = bpContractorCertDao.save(bpContractorCert);
        //添加通知
        int flag = 0;
        LocalDate certExpireDate = bean.getCertExpireDate();
        flag = notifyByCurData(id, save.getDutyScriptRemindOrNot(), flag, certExpireDate);
        if (flag == 1) {
            //判断有没有提醒配置
            Pair<Boolean, BpContractorCertRemind> pair = remindOrNot();
            if (pair.getKey()) {
                List<CommonIndexNotify> notifyList = Lists.newArrayList();
                //需要通知的人员ids
                BpContractorCertRemind remind = pair.getValue();
                List<Long> remindUserIdList = getRemindUserIdList(remind);
                Integer hours = CertificateRemindTypes.getHours(remind.getRemindType());
                //承包商资质证书
                getContractorQualityCert(hours, remindUserIdList, notifyList, save);
                notifyDao.saveAll(notifyList);
                save.setDutyScriptRemindOrNot(1);
                bpContractorCertDao.save(save);
            }
        }
        return ResultBean.success(save.getId());
    }

    @Override
    public ResultBean contractorCertNullify(Long id) {
        bpContractorCertDao.contractorCertNullify(id);
        return ResultBean.defaultSuccessResult();
    }

    @Override
    public ResultBean certRemindSave(BpCertExpireRemindBean bean) {
        Integer expireRemindOrNot = bean.getExpireRemindOrNot();
        if (expireRemindOrNot == 1) {
            Assert.notNull(bean.getRemindType(), "提醒类型不能为空");
            Assert.notNull(bean.getUserDepartFlag(), "userDepartFlag cannot be null");
            judgeUserDepartFlag(bean);
        } else {
            if (bean.getUserDepartFlag() != null) {
                judgeUserDepartFlag(bean);
            }
        }
        Long id = bean.getId();
        BpContractorCertRemind remind;
        if (id == null) {
            List<BpContractorCertRemind> all = bpContractorCertRemindDao.findAll();
            if (!CollectionUtils.isEmpty(all)) {
                return ResultBean.fail(101, "当前已有数据");
            }
            remind = new BpContractorCertRemind();
            remind.setState(DataStateTypes.EFFECTIVE.getState());
        } else {
            remind = bpContractorCertRemindDao.findById(id).orElseThrow(() -> new IllegalArgumentException("数据不存在"));
            if (DataStateTypes.UN_EFFECTIVE.getState().equals(remind.getState())) {
                return ResultBean.fail(101, "此数据已作废");
            }
        }
        BeanUtils.copyProperties(bean, remind, "state");
        List<Long> remindUserIds = bean.getRemindUserIds();
        remind.setRemindUserIdJson(JSON.toJSONString(remindUserIds));
        BpContractorCertRemind save = bpContractorCertRemindDao.save(remind);
        if (save.getExpireRemindOrNot() == 1) {
            Integer hours = CertificateRemindTypes.getHours(bean.getRemindType());
            if (hours == null) {
                throw new IllegalArgumentException("此提醒类型不支持");
            }
            //需要通知的人员ids
            List<Long> remindUserIdList = getRemindUserIdList(save);
            if (CollectionUtils.isEmpty(remindUserIdList)) {
                return ResultBean.defaultSuccessResult();
            }
            List<CommonIndexNotify> notifyList = Lists.newArrayList();
            //承包商责任书
            List<BpContractor> bpContractorList = dao.findRemindTask();
            if (!CollectionUtils.isEmpty(bpContractorList)) {
                for (BpContractor contractor : bpContractorList) {
                    getContractorDutyNotifyList(hours, remindUserIdList, notifyList, contractor);
                    //置提醒位
                    contractor.setDutyScriptRemindOrNot(1);
                }
                dao.saveAll(bpContractorList);
            }
            //承包商资质证书
            List<BpContractorCert> bpContractorCertList = bpContractorCertDao.findRemindTask();
            if (!CollectionUtils.isEmpty(bpContractorCertList)) {
                for (BpContractorCert cert : bpContractorCertList) {
                    getContractorQualityCert(hours, remindUserIdList, notifyList, cert);
                    cert.setDutyScriptRemindOrNot(1);
                }
                bpContractorCertDao.saveAll(bpContractorCertList);
            }
            notifyDao.saveAll(notifyList);
        }
        return ResultBean.defaultSuccessResult();
    }

    private void judgeUserDepartFlag(BpCertExpireRemindBean bean) {
        if (bean.getUserDepartFlag() == 0) {
            Assert.notNull(bean.getRemindUserIds(), "userDepartFlag和实际不匹配");
        } else {
            Assert.notNull(bean.getDepartId(), "userDepartFlag和实际不匹配");
        }
    }

    private void getContractorQualityCert(Integer hours, List<Long> remindUserIdList, List<CommonIndexNotify> notifyList, BpContractorCert cert) {
        LocalDate certExpireDate = cert.getCertExpireDate();
        LocalDateTime expireTime = LocalDateTime.of(certExpireDate, LocalTime.of(0, 0, 0));
        LocalDateTime needNotifyTime = expireTime.minusHours(hours);
        Long certId = cert.getId();
        for (Long aLong : remindUserIdList) {
            CommonIndexNotify notify = new CommonIndexNotify();
            notify.setUserId(aLong);
            notify.setEduCertUserId(certId);
            notify.setRemindDateTime(needNotifyTime);
            notify.setRemindDate(needNotifyTime.toLocalDate());
            notify.setType(CommonIndexNotifyTypes.CONTRACTOR_QUALITY_CERT.getType());
            String format = certExpireDate.format(DateTimeFormatter.ofPattern("MM月dd日"));
            notify.setNotifyMessage(cert.getCertName() + "资质证书" + format + "即将过期");
            notifyList.add(notify);
        }
    }

    private void getContractorDutyNotifyList(Integer hours, List<Long> remindUserIdList, List<CommonIndexNotify> notifyList, BpContractor contractor) {
        LocalDate dutyScriptExpireDate = contractor.getDutyScriptExpireDate();
        LocalDateTime expireTime = LocalDateTime.of(dutyScriptExpireDate, LocalTime.of(0, 0, 0));
        LocalDateTime needNotifyTime = expireTime.minusHours(hours);
        Long contractorId = contractor.getId();
        for (Long aLong : remindUserIdList) {
            CommonIndexNotify notify = new CommonIndexNotify();
            notify.setEduCertUserId(contractorId);
            notify.setUserId(aLong);
            notify.setRemindDateTime(needNotifyTime);
            notify.setRemindDate(needNotifyTime.toLocalDate());
            notify.setType(CommonIndexNotifyTypes.CONTRACTOR_DUTY_CERT.getType());
            String format = dutyScriptExpireDate.format(DateTimeFormatter.ofPattern("MM月dd日"));
            notify.setNotifyMessage(contractor.getCompanyName() + "的责任书" + format + "即将过期");
            notifyList.add(notify);
        }
    }

    private List<Long> getRemindUserIdList(BpContractorCertRemind save) {
        Long departId = save.getDepartId();
        String remindUserIdJson = save.getRemindUserIdJson();
        List<Long> userIdList = Lists.newArrayList();
        if (save.getUserDepartFlag() == 0) {
            userIdList.addAll(JSON.parseArray(remindUserIdJson, Long.class));
        } else {
            userIdList.addAll(baseUserDao.findIdByDepartId(departId));
        }
        return userIdList;
    }

    @Override
    public ResultBean certRemindGet() {
        BpContractorCertRemind remind = getRemind();
        if (remind == null) {
            return ResultBean.success(null);
        }
        return ResultBean.success(convertRemind(remind));
    }

    @Override
    public ResultBean companyList() {
        List<BpEnterpriseInfo> list = bpEnterpriseInfoDao.findAll();
        List<BpContractorNameDto> resultList = (List<BpContractorNameDto>) allContractor().getData();
        resultList = resultList == null ? Lists.newArrayList() : resultList;
        for (BpEnterpriseInfo info : list) {
            resultList.add(new BpContractorNameDto(info.getId(), info.getName(), 0));
        }
        return ResultBean.success(resultList);
    }

    private BpContractorCertRemind getRemind() {
        List<BpContractorCertRemind> list = bpContractorCertRemindDao.findAll();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<BpContractorCertRemind> collect = list.stream().filter(r ->
                DataStateTypes.EFFECTIVE.getState().equals(r.getState())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            return null;
        }
        BpContractorCertRemind remind = collect.get(0);
        return remind;
    }

    private BpCertExpireRemindBean convertRemind(BpContractorCertRemind remind) {
        BpCertExpireRemindBean bpCertExpireRemindBean = new BpCertExpireRemindBean();
        BeanUtils.copyProperties(remind, bpCertExpireRemindBean);
        if (remind.getUserDepartFlag() != null && remind.getUserDepartFlag() == 0) {
            List<EduCertEditUserNameBean> collect1 = baseUserDao.findAllById(JSON.parseArray(remind.getRemindUserIdJson(), Long.class)).stream().map(r ->
                    new EduCertEditUserNameBean(r.getId(), r.getRealName())).collect(Collectors.toList());
            bpCertExpireRemindBean.setUserNames(collect1);
        } else if (remind.getUserDepartFlag() != null && remind.getUserDepartFlag() == 1) {
            Long departId = remind.getDepartId();
            String departName = bpDepartDao.getNameById(departId);
            bpCertExpireRemindBean.setDepartName(new EduCertEditUserNameBean(departId, departName));
        }
        return bpCertExpireRemindBean;
    }

    private Pair<Boolean, BpContractorCertRemind> remindOrNot() {
        BpContractorCertRemind remind = getRemind();
        if (remind == null || remind.getExpireRemindOrNot() == 0) {
            return new Pair<>(false, null);
        }
        return new Pair<>(true, remind);
    }

    private <T> List<T> convertJsonToList(String s, Class<T> clazz) {
        if (s == null) {
            return null;
        }
        return JSON.parseArray(s, clazz);
    }

    private String getListJson(List list) {
        list = list == null ? Lists.newArrayList() : list;
        return JSON.toJSONString(list);
    }


    @Override
    public List<Long> findIdsByName(String name) {
        return dao.findIdsByName(name);
    }

    @Override
    public Page<SimpleInfoBean> simplePage(Pageable page, String nameOrCode) {
        Page<BpContractor> contractorPage = dao.findSimplePage(nameOrCode, ContractorTypeEnum.QUALIFIED.getDesc(), page);
        return PageDataUtils.convertPageData(contractorPage, f -> {
            SimpleInfoBean bean = new SimpleInfoBean();
            bean.setName(f.getCompanyName());
            bean.setId(f.getId());
            bean.setCode(f.getCode());
            return bean;
        });
    }

    @Override
    public void batchSyncData(List<BpContractor> datas) {
        if (baseConfigService.checkIfSync()) {
            orientationDataSyncService.contractor(datas, "saveContractor");
        }
    }

}
